package com.hmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.IsearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Azer
 * @LOVE,,,
 * @Date 2021/11/7 19:41
 */
@Service
public class SearchService extends ServiceImpl<SearchMapper,Item> implements IsearchService {

    @Qualifier("restHighLevelClient")
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    /**
     * 监听商品下架
     * @param id
     */
    @Override
    public void ListenItemDelete(Long id) throws IOException {
        DeleteRequest request=new DeleteRequest("item",String.valueOf(id));
        client.delete(request,RequestOptions.DEFAULT);
    }

    /**
     * 监听上架
     * @param id
     */
    @Override
    public void ListenItemInsert(Long id) throws IOException {
//        Item item = getById(id);
        Item item = itemClient.QueryById(id);
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest indexRequest=new IndexRequest("item");
        indexRequest.id(String.valueOf(item.getId()));
        indexRequest.source(JSON.toJSONString(itemDoc),XContentType.JSON);

        client.index(indexRequest,RequestOptions.DEFAULT);

    }

    /**
     * 搜索
     *
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {

        SearchRequest request = new SearchRequest("item");
        buildBasicQuery(params, request);

        //分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);


        //排序

        String sortBy = params.getSortBy();
        //价格
        if ("price".equals(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        }
        //销量
        if ("sold".equals(sortBy)) {
            request.source().sort("sold", SortOrder.DESC);
        }

        //高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            return handleResponse(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //搜索条件设置
        SearchRequest request = new SearchRequest("item");
        buildBasicQuery(params, request);
        request.source().size(0);
        //聚合
        buildAggregation(request);

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取聚合结果
            Aggregations aggregations = response.getAggregations();
            //解析结果
            Map<String, List<String>> result = new HashMap<>();
            List<String> brandAggList = getAggByName(aggregations, "brand_agg");
            result.put("brand", brandAggList);

            List<String> categoryAggList = getAggByName(aggregations, "category_agg");
            result.put("category", categoryAggList);


            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根绝聚合名称获取聚合结果
        Terms brandAgg = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        //遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            //获取key
//                brandAggBucket.getKeyAsString();
            //加入集合
            list.add(brandAggBucket.getKeyAsString());
        }
        return list;
    }


    //聚合
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(
                AggregationBuilders.terms("brand_agg")
                        .field("brand")
                        .size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("category_agg")
                        .field("category")
                        .size(20)
        );

    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        //分类
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        //品牌
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        // 价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
           boolQueryBuilder.filter(QueryBuilders
                   .rangeQuery("price")
                   .gte(params.getMinPrice()*100)
                   .lte(params.getMaxPrice()*100)

           );
        }
//        request.source().query(boolQueryBuilder);

        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询，相关性算分的查询
                boolQueryBuilder,
                //function score数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中一个function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        request.source().query(functionScoreQuery);


    }

    /**
     * 自动补全功能
     *
     * @return
     */
    @Override
    public List<String> suggestion(String key) {
        //准备request
        SearchRequest request = new SearchRequest("item");
        //准备DSL
        request.source().size(0);
        request.source().suggest(
                new SuggestBuilder().addSuggestion(
                        "suggestions", //自定义查询名称
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(key)
                                .skipDuplicates(true)
                                .size(10)
                )
        );
        //发起请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据查询补全名称,获取补全结果
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            return list;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //3.解析响应
        SearchHits hits = response.getHits();
        //总条数
        long total = hits.getTotalHits().value;

        //获取文档数组
        SearchHit[] searchHits = hits.getHits();

        //遍历
        List<ItemDoc> itemDocList = new ArrayList<>(searchHits.length);

        //遍历文档数组 获取数据
        for (SearchHit hit : searchHits) {
            //获取source
            String jsonStr = hit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = JSON.parseObject(jsonStr, ItemDoc.class);

//            获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    //获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    //覆盖高亮结果
                    itemDoc.setName(name);
                }
            }

            //加入集合
            itemDocList.add(itemDoc);
        }

        PageDTO<ItemDoc> result = new PageDTO<>();
        result.setTotal(total);
        result.setList(itemDocList);


        return result;

    }
}
